package com.qingke.oms.command.shop;

import java.util.List;

import com.qingke.oms.command.ShopCommand;
import com.qingke.oms.pojo.Order;
import com.qingke.oms.pojo.Shop;
import com.qingke.oms.pojo.User;
import com.qingke.oms.util.OMSConsole;

public class DeliveryCommand extends ShopCommand implements UpdateGoodsStatistic{

	public DeliveryCommand(User user, Shop shop) {
		super(user, shop);
	}

	@Override
	public void execute() {
		if(user.getId()!=shop.getOwnerId()){
			OMSConsole.println("It's not your shop,you can't delivery goods.");
			return ;
		}
		
		String cmd;
		while(true){
			cmd=OMSConsole.prompt("delivery>");
			if("all".equalsIgnoreCase(cmd)){
				all();
			}
			else if("id".equalsIgnoreCase(cmd)){
				id();
			}
			else if("help".equalsIgnoreCase(cmd)){
				OMSConsole.println("- all    delivery all orders that wait delivery");
				OMSConsole.println("- id     delivery the id of the orders that wait delivery");
				OMSConsole.println("- exit   exit delivery");
			}
			else if("exit".equalsIgnoreCase(cmd)){
				break;
			}
			else{
				OMSConsole.println("err input");
				continue;
			}
		}
	}
	private void all(){
		List<Order> list=dao.selectOrderByShopIdAndStatus(shop.getId(),"wait_delivery");
		if(list.size()==0){
			OMSConsole.println("There is no order that need be deliveried.");
			return ;
		}
		int count=0;
		for(Order order:list){
			boolean isSuccess=dao.insertTransactionStatusRecord(order.getId(), "shipped");
			if(isSuccess){
				if(dao.insertShipmentRecord(order, "already shipped")){
					count++;
				}
			}
		}
		if(count!=list.size()){
			OMSConsole.println("delivery all orders failed.");
			return ;
		}
		OMSConsole.println("delivery all order success.");
		updateGoodsStatistic();
	}
	private void id(){
		List<Order> list=dao.selectOrderByShopIdAndStatus(shop.getId(),"wait_delivery");
		if(list.size()==0){
			OMSConsole.println("There is no order that need be deliveried.");
			return ;
		}
		
		int id=OMSConsole.getInt("id:");
		Order order=dao.selectOrderById(id);
		if(order==null){
			OMSConsole.println("The id of the order is not existed.");
			return ;
		}
		if(!list.contains(order)){
			OMSConsole.println("The order is not the order that you need delivery.");
			return ;
		}
		boolean isSuccess=dao.insertTransactionStatusRecord(order.getId(), "shipped");
		if(!isSuccess||!dao.insertShipmentRecord(order, "already shipped")){
			OMSConsole.println("The order delivery failed.");
			return ;
		}
		OMSConsole.println("The order delivery success.");
		updateGoodsStatistic();
		
	}

}
